package com.wisemoresystem.seal.base;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.wisemoresystem.seal.model.t_user;
import com.wisemoresystem.seal.service.UserService;
import com.wisemoresystem.seal.util.SpringTools;
import com.wisemoresystem.seal.web.SessionVal;
import com.wisemoresystem.seal.web.WebTools;

public class MySessionListener implements HttpSessionListener,
		HttpSessionAttributeListener {

	private UserService s;

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub】
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {

		if (s == null) {
			s = (UserService) SpringTools.getWebBean(UserService.class);
		}

		if (se.getName().equals(SessionVal.login_user)) {

			String sessionId = se.getSession().getId();

			t_user user = WebTools.getCurrentUser();
			user = s.findObjById(user.get_id(), t_user.class);

			HttpSession sn = (HttpSession) se.getSession().getServletContext()
					.getAttribute(user.get_id());

			se.getSession().getServletContext()
					.setAttribute(user.get_id(), WebTools.getSession());
			if (sn != null) {
				sn.invalidate();
			}

			user.setIs_live("在线");
			user.setSession_id(sessionId);
			s.updateObj(user);

			System.err.println("用户上线--->" + user.getUname());

		}

	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub
		if (SessionVal.login_user.equals(se.getName())) {
			t_user user = (t_user) se.getValue();
			System.err.println("用户下线:" + user.getUname());
			HttpSession sn = (HttpSession) se.getSession().getServletContext()
					.getAttribute(user.get_id());
			if (sn == se.getSession()) {
				se.getSession().getServletContext()
						.removeAttribute(user.get_id());

				t_user userDb = s.findObjById(user.get_id(), t_user.class);
				userDb.setIs_live("离线");
				userDb.setSession_id("");
				s.updateObj(userDb);

			} else {
				// 不移除
			}
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		// TODO Auto-generated method stub

	}

}